package cn.nexd.app.collector.Thread;

import android.content.ContentValues;
import android.content.Context;

import java.util.ArrayList;
import java.util.List;

import cn.nexd.app.collector.application.NexdApplication;
import cn.nexd.sdk.location.bean.IndoorLocationResultRecordBean;
import cn.nexd.utils.framework.tools.Logger;
import cn.nexd.utils.framework.tools.StringUtil;

/**
 * Created by wangxu on 16/12/19.
 */

public class RecordThread extends Thread {


    private static final String TAG = "RecordThread";
    private Context context;
    private static final List<List<IndoorLocationResultRecordBean>> queue = new ArrayList<>();


    private static RecordThread recordThread;


    public int getQueueSize() {
        return queue.size();
    }


    private RecordThread() {


    }

    public void setContext(Context context) {
        this.context = context;
    }

    public static RecordThread getRecordThread() {
        if (recordThread == null) {
            recordThread = new RecordThread();
            Logger.debug(TAG, "getRecordThread: 创建记录数据线程");
        }
        return recordThread;
    }


    public void add(List<IndoorLocationResultRecordBean> indoorLocationResultRecordBeen) {
        queue.add(indoorLocationResultRecordBeen);
    }

    @Override
    public void run() {
        while (true) {
            if (queue.size() > 0) {
                record(queue.get(0));
                queue.remove(0);
            }
        }
    }

    @Override
    public synchronized void start() {
        if (isAlive()) {
            Logger.debug(TAG, "start: alived , needn`t restart");
            return;
        }
        super.start();

    }

    private void record(List<IndoorLocationResultRecordBean> list) {
        if (list == null) {
            return;
        }
        if (!NexdApplication.getInstance().getSqlHelper().tableIsExist("mall_" + list.get(0).getBuildingId())) {
            NexdApplication.getInstance().getSqlHelper().getDb().execSQL("create table mall_" + list.get(0).getBuildingId() + "(mallId, floorId ,position, signal, date)");
        }

        Logger.debug(TAG, "record: size = " + list.size());
        for (IndoorLocationResultRecordBean indoorLocationResultRecordBean : list) {
            ContentValues value = new ContentValues();
            value.put("mallId", indoorLocationResultRecordBean.getBuildingId());
            value.put("floorId", indoorLocationResultRecordBean.getFloorId());
            value.put("position", indoorLocationResultRecordBean.getIndoorLocationResult());
            value.put("signal", StringUtil.compress(indoorLocationResultRecordBean.getIndoorLocationDataList()));
            value.put("date", indoorLocationResultRecordBean.getDate());
            NexdApplication.getInstance().getSqlHelper().insertIfNotExist("mall_" + indoorLocationResultRecordBean.getBuildingId(), value);
        }

        Logger.debug(TAG, "record: save finished");
    }
}
